package com.luo.controller;

import com.alibaba.fastjson.JSON;
import com.luo.model.Goods;
import com.luo.model.Result;
import com.luo.service.ClassService;
import com.luo.service.GoodService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

/**
 * 功能：添加一个商品
 * 作者：Luo。
 * 日期：2024/1/14 15:58
 */
@WebServlet("/addOneGood")
public class AddOneGoodController extends HttpServlet {

    ClassService classService = new ClassService();
    GoodService goodService = new GoodService();
    Result result = new Result();

    @Override
    protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        String hotNum = req.getParameter("hotNum");
        String money = req.getParameter("money");
        String oneKind = req.getParameter("oneKind");
        String twoKind = req.getParameter("twoKind");
        String desc = req.getParameter("desc");
        String inventory = req.getParameter("inventory");
        String discount = req.getParameter("discount");
        String shopName = req.getParameter("shopName");
        String picture = req.getParameter("picture");

        oneKind = classService.queryOneClassByName(oneKind);
        twoKind = classService.queryTwoClassByName(twoKind);

        Random random = new Random();
        StringBuffer shopId = new StringBuffer("");
        for (int i = 0; i < 8; i++) {
            shopId.append(random.nextInt(10));
        }

        Goods goods = new Goods();
        goods.setName(shopName);
        goods.setId(Integer.parseInt(shopId.toString()));
        goods.setPicture(picture);
        goods.setHotNum(hotNum);
        goods.setInventory(inventory);
        goods.setDiscount(discount);
        goods.setDesc(desc);
        goods.setPrice(money);
        goods.setOneClassId(oneKind);
        goods.setTwoClassId(twoKind);

        int i = goodService.addOneGood(goods);

        result.setCode("" + i);
        result.setMsg("添加成功");
        String jsonString = JSON.toJSONString(result);
        resp.getWriter().write(jsonString);
        resp.getWriter().close();
    }
}
